import { login, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    projects: [], // 工程列表数据
    avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
    permissions: [],
    projectsId: '',
    user: {},
    title: '智慧工地',
    logo: '../../../assets/images/logo.png'
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
    // console.log(Object.assign(state, getDefaultState()))
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_USER: (state, user) => {
    state.user = user
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  // 工程列表数据
  SET_PROJECTS: (state, projects) => {
    state.projects = projects
  },
  // 工程id
  SET_PROJECTSID: (state, projectsId) => {
    state.projectsId = projectsId
  },
  // 权限
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const data = {
      captcha: userInfo.captcha_code,
      captchaId: userInfo.captchaId,
      password: userInfo.password,
      rememberMe: userInfo.rememberMe,
      userName: userInfo.userName
    }
    return new Promise((resolve, reject) => {
      login(data).then(response => {
        const { data } = response
        if (!data.isFirst) {
          commit('SET_USER', data.userRsp || {})
          commit('SET_PROJECTS', data.projects || [])
          // commit('SET_PERMISSIONS', data.permissions)
          if (data.projects) {
            commit('SET_PROJECTSID', data.projects[0].id)
          } else {
            data.projects = []
          }
        }
        // setToken(data.token)
        setToken('1qaz2wsxcde3rfs3rfsf')
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout().then((response) => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        window.localStorage.clear()
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

